package cn.shopifymall.studying.classloader;


import cn.shopifymall.studying.spi.SalaryCalService;

import java.util.Iterator;
import java.util.ServiceLoader;

/**
 * 封装 ContextClassLoader
 *
 * @Author 孤风雪影
 * @Email gitee.com/efairy520
 * @Date 2025/1/16 10:23
 * @Version 1.0
 */
public class OADemo05 {
    public static void main(String[] args) throws Exception {
        Double money = 2000.0;
        while (true) {
            SalaryJarLoader salaryJarLoader1 = new SalaryJarLoader("D:\\kit1\\swift-kit.jar");
            SalaryCalService service1 = getSalaryCalService(salaryJarLoader1);
            System.out.println("原本的工资 = " + service1.cal(money));

            SalaryJarLoader salaryJarLoader2 = new SalaryJarLoader("D:\\kit2\\swift-kit.jar");
            SalaryCalService service2 = getSalaryCalService(salaryJarLoader2);
            System.out.println("修改后的工资 = " + service2.cal(money));

            Thread.sleep(1000);
        }
    }

    private static SalaryCalService getSalaryCalService(SalaryJarLoader salaryJarLoader) {
        SalaryCalService service = null;
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        try {
            Thread.currentThread().setContextClassLoader(salaryJarLoader);
            ServiceLoader<SalaryCalService> services1 = ServiceLoader.load(SalaryCalService.class);
            Iterator<SalaryCalService> iterator = services1.iterator();
            if (iterator.hasNext()) {
                service = iterator.next();
            }
        } finally {
            Thread.currentThread().setContextClassLoader(cl);
        }
        return service;
    }
}
